package com.klikmee.sms.core.commons.exceptions;

import org.apache.log4j.Logger;

/**
 * Default implementation of {@link ExceptionHandler} interface. Adds
 * 
 * @author makcro
 * 
 */
public class DefaultExceptionHandler implements ExceptionHandler {

	/**
	 * Logger implementation
	 */
	private Logger	logger	= Logger.getLogger(DefaultExceptionHandler.class);

	/**
	 * Handles exceptions by examining their base class. If base class is
	 * {@link InternalException} then it adds INTERNAL flag to it, if base class
	 * is {@link ServiceException} than flag is SERVICE Other exceptions are
	 * intact and logged normally.
	 * 
	 */
	@Override
	public void handle(Exception exception) {
		// check the root of the exception
		if (exception instanceof InternalException) {
			// append internal flag
			String message = buildInternalExceptionMessage((InternalException) exception);
			logger.fatal(message, exception);
		}

		else if (exception instanceof ServiceException) {
			// append service flag
			String message = buildServiceExceptionMessage((ServiceException) exception);
			logger.fatal(message, exception);
		}

		else {
			logger.fatal("Unexpected error occurred", exception);
		}
	}

	/**
	 * Builds string message for the internal exception including
	 * error info and flags used for logging.
	 * @param exception
	 * @return
	 */
	private String buildInternalExceptionMessage(InternalException exception) {
		StringBuilder logMessageBuilder = new StringBuilder();
		// append flag
		logMessageBuilder.append(ExceptionHandler.INTERNAL_EXCEPTOIN_FLAG).append(" - ").append(exception.getMessage());
		// append error context
		logMessageBuilder.append("\n");
		logMessageBuilder.append(ErrorInfo.extractErrorId(exception));
		logMessageBuilder.append("\n").append("\n");
		logMessageBuilder.append(ErrorInfo.extractParameters(exception)).append("\n");
		
		return logMessageBuilder.toString();
	}
	
	private String buildServiceExceptionMessage(ServiceException exception){
		StringBuilder logMessageBuilder = new StringBuilder();
		// append flag
		logMessageBuilder.append(ExceptionHandler.SERVICE_EXCEPTOIN_FLAG).append(" - ").append(exception.getMessage());
		// append error context
		logMessageBuilder.append("\n");
		logMessageBuilder.append(ErrorInfo.extractErrorId(exception));
		logMessageBuilder.append("\n").append("\n");
		logMessageBuilder.append(ErrorInfo.extractParameters(exception)).append("\n");
		
		return logMessageBuilder.toString();
	}
}
